<template>
    <view class="container">
        <!-- @scrolltolower="scrolltolower" -->
        <view>
            <view class="tab-radius">
                <tab-radius :list="['统计分析', '投保明细']" :active="payIndex" @change="onPayTab" divided="100%" />
            </view>
            <!-- 详细订单 -->
            <view class="record-list">
                <recharge :payIndex="payIndex" />
            </view>
            <!-- 销售记录 -->
            <view class="operate-box" v-show="payIndex === 0">
                <!-- 保险数据模块 -->
                <view class="bosom">
                    <view class="row">
                        <view class="vendition">保险数据</view>
                        <view class="align-flex">
                            <picker @change="bindPickerChangeCompany" :range="allInsCompany">
                                <view class="fatalism align-flex fatalism-right">
                                    <view class="uni-input">{{ allInsCompany[sortIndex] || '暂无' }}</view>
                                    <image class="fatalism-dropdown" src="/static/achievement-reports-form/dropdown.png" />
                                </view>
                            </picker>
                            <picker @change="bindPickerChange" :value="datePlan" :range="insuranceDate">
                                <view class="fatalism fatalism-right">

                                    <view class="row">
                                        <view class="uni-input">{{
                                            insuranceDate[datePlan]
                                        }}</view>
                                        <img class="transverse-down" src="/static/score/dropdown.png" alt="" />
                                    </view>
                                    <view>
                                    </view>
                                </view>
                            </picker>
                            <view class="align-flex">
                                <view class="previously align-flex">
                                    <poput-time :list="selectTimeList" :default="timeIndex" @cancel="onCancel" />
                                </view>
                            </view>
                        </view>
                    </view>
                    <view class="block-box-i block-box-i-active">
                        <view class="title">保费</view>
                        <view class="num">¥{{ insureDate?.amount }}</view>
                    </view>
                    <view class="box-list align-flex">
                        <view class="block-box-i">
                            <view class="title">投保人数</view>
                            <view class="num">{{
                                insureDate?.policyPeopleCount
                            }}</view>
                        </view>
                        <view class="block-box-i block-box-i-left">
                            <view class="title">报案数</view>
                            <view class="num">{{
                                insureDate?.recordCount
                            }}</view>
                        </view>
                    </view>
                </view>
                <!-- 饼图模块 -->
                <view class="bosom">
                    <view class="row">
                        <view class="vendition">方案统计</view>
                        <picker mode="date" fields="month" :value="date" @change="bindDateChange">
                            <view class="screen-i">

                                {{ date
                                }}
                                <image class="drop-down" src="@/static/drop-down.png" mode="scaleToFill" />
                            </view>
                        </picker>
                    </view>
                    <view class="operate-chart">
                        <no-data v-if="chartsDataPie1.series[0].data.length === 0
                            " />
                        <qiun-data-charts v-show="chartsDataPie1.series[0].data.length" canvas2d canvasId="operate-ring"
                            class="qiun-data-charts" type="ring" :opts="optsRing" :chartData="chartsDataPie1" />
                    </view>
                    <view class="operate-table">
                        <view class="table-title row">
                            <view class="title">保险方案</view>
                            <view class="title">保费</view>
                            <view class="title">占比</view>
                        </view>
                        <view class="table-cell row" v-for="(item, index) in statisticsData" :key="index">
                            <view class="cell cell-ac tive cell-align">
                                <view :style="{ background: item.color }" class="colour-block"></view>
                                {{ item.programme }}
                            </view>
                            <view class="cell">¥{{ item.premium }}</view>
                            <!-- {{((item.money/item.total).toString() == 'NaN' ? 0 : item.money/item.total * 100).toFixed(2) + '%'}} -->
                            <view class="cell">{{
                                item.totalPremium > 0
                                ? (
                                    (item.premium /
                                        item.totalPremium) *
                                    100
                                ).toFixed(2) + '%'
                                : '暂无'
                            }}</view>
                        </view>
                    </view>
                </view>
                <!-- 运营数据模块 -->
                <view class="bosom">
                    <view class="row">
                        <view class="vendition">运营数据</view>
                        <view class="align-flex">
                            <poput-time :list="operateData" :default="operateIndex" @cancel="bindPickerChangeOperate"
                                noCustom="true" />
                        </view>
                    </view>
                    <view class="box-list align-flex">
                        <view class="block-box-i">
                            <view class="title">开通客户</view>
                            <view class="num">{{ operate.openCount }}</view>
                        </view>
                        <view class="block-box-i block-box-i-left">
                            <view class="title">充值金额</view>
                            <view class="num">¥{{ operate.rechargeAmount }}</view>
                        </view>
                    </view>
                    <view class="box-list align-flex">
                        <view class="block-box-i">
                            <view class="title">充值客户数</view>
                            <view class="num">{{ operate.integer }}</view>
                        </view>
                        <view class="block-box-i block-box-i-left">
                            <view class="title">充值并使用的客户数</view>
                            <view class="num">{{
                                operate.rechargeAndUse
                            }}</view>
                        </view>
                    </view>
                </view>
                <!-- 近7日开通趋势图表模块 -->
                <view class="bosom">
                    <view class="row trend-row">
                        <view class="vendition">近7日开通趋势</view>
                        <view class="jamb align-flex">
                            <view class="graphic"></view>
                            <view class="dredge">开通数</view>
                        </view>
                    </view>
                    <view class="charts-box">
                        <qiun-data-charts canvas2d canvasId="operate-two" type="column" :opts="opts"
                            :chartData="chartData" />
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import tabRadius from '@/components/tab-radius/tab-radius.vue'
import uchartsOpts from '@/utils/ucharts'
import recharge from '@/packageQuick/pages/day-to-day/recharge/recharge.vue'
import {
    getDredgeCurrent,
    getInsureData,
    getInsurePlanData,
    getMethodStatistics,
    getOperateData,
    OperateDataDto,
    getDayAllCompany
} from '@/api/quick'
import { onLoad, onReachBottom } from '@dcloudio/uni-app'
import user from '@/utils/user'
import poputTime from '@/components/popup-custom-time/popup-custom-time.vue'
import noData from '@/components/no-data/no-data.vue'
import { toNumber } from '@vue/shared'
import { compare, getDigits } from '@/utils/util'
import { share } from '@/utils/share'

onLoad(async () => {
    const nowyear = new Date().getFullYear()
    const nowmonth = new Date().getMonth() + 1
    startTime.value = formatDate(new Date(nowyear, nowmonth - 1, 1))
    endTime.value = formatDate(new Date(nowyear, nowmonth, 0))
    allCompany.value = await getDayAllCompany(1)
    console.log(allCompany.value, 'allCompanyallCompanyallCompany')
    // push 推送  合并数组
    allCompany.value.forEach((item: any, index: number) =>
        longCompanyName.value = [{ ...[allCompany.value[index].insurCompany, allCompany.value[index].name] }, ...longCompanyName.value]
    )
    // longCompanyName.value = [...['全部保司']],
    console.log(longCompanyName.value, 'allCompanyallCompany')
    longCompanyName.value.forEach((item: any, index: number) => {
        console.log(item[0], item[1], '000000000000000000000')
        allInsCompany.value[index + 1] = item[1] // 每一项赋值进去。
    })
    allInsCompany.value[0] = '全部保司' // 第0项赋值
    console.log(allInsCompany.value, '111111111111111111111111111111111')
    share()
})
const formatDate = (date: any) => {
    const myyear = date.getFullYear()
    let mymonth = date.getMonth() + 1
    let myweekday = date.getDate()
    if (mymonth < 10) {
        mymonth = "0" + mymonth
    }
    if (myweekday < 10) {
        myweekday = "0" + myweekday
    }
    return (myyear + "-" + mymonth + "-" + myweekday)
}
// eslint-disable-next-line no-redeclare
// function share () {
//   wx.showShareMenu({
//     withShareTicket: true,
//     /* //设置下方的Menus菜单，才能够让发送给朋友与分享到朋友圈两个按钮可以点击 */
//     menus: ["onShareAppMessage", "onShareTimeline"]
//   })
// }

const allInsCompany = ref([] as string[])
// 到达底部
onReachBottom(() => {
    if (payIndex.value == 1) {
        uni.$emit('onReachBottom')
    } else {
    }
})

const allCompany = ref()

const chartsDataColumn1 = ref({})

const insureDate = ref()
/* ucharts柱状图操作图表 */
const chartData = ref({
    categories: [],
    series: [
        {
            name: '',
            data: [],
            show: true,
            textColor: '#9EAFFA'
        }
    ]
})
const opts = ref({
    background: 'rgba(250, 250, 252, 1)',
    padding: [25, 15, 0, 5],
    dataLabel: false,
    legend: {
        show: false,
        position: 'top',
        float: 'right',
        padding: 0,
        margin: 5,
        fontSize: 8
    },
    xAxis: {
        axisLine: true,
        disableGrid: true,
        fontSize: 10,
        axisLineColor: '#F4F4F7'
    },
    yAxis: {
        disabled: false,
        disableGrid: false,
        data: [
            {
                min: 0,
                axisLine: false
            }
        ]
    },
    extra: {
        column: {
            type: 'group',
            width: 10,
            activeBgColor: '#000000',
            activeBgOpacity: 0.08,
            seriesGap: 0
        }
    }
})
// 模拟从服务器获取数据时的延时
// 模拟服务器返回数据，如果数据格式和标准格式不同，需自行按下面的格式拼接

/* 饼图数据模块 */
const chartsDataPie1 = ref({
    series: [
        {
            data: []
        }
    ]
})

const payIndex = ref(0)
const optsRing = ref(uchartsOpts.optsRing)

// tab发薪胶囊回调
const onPayTab = (index: number) => {
    payIndex.value = index
}

// 保险方案 变量
const datePlan = ref(0)
const insuranceDate = ref([] as string[])

// 改变保险方案事件
const bindPickerChange = (e: any) => {
    datePlan.value = e.detail.value
    console.log('picker发送选择改变，携带值为', e.detail.value)
    insuranceData()
}

// 运营数据  昨天、明天、本周、本月、自定义
const operateIndex = ref(4)
const operateData = ref(['全部', '昨天', '今天', '本周', '本月', '上月'])
const itemRangeThree = ref()
const itemRangeFour = ref()
const startTime = ref('')
const endTime = ref('')
const bindPickerChangeOperate = async (
    index: number,
    time: undefined | string
) => {
    console.log(index, 'operateData')
    //   console.log(e.detail, 'e.detail')
    operateIndex.value = index.index
    itemRange.value = index.time
    itemRangeThree.value = itemRange.value.substring(0, 10)
    itemRangeFour.value = itemRange.value.substring(13, 23)
    startTime.value = index.startTime || ''
    endTime.value = index.endTime || ''
    await OperateData()
}

// 调用保险方案接口
const insurancePlan = async () => {
    const result = await getInsurePlanData()
    result.unshift({ planAlias: '全部方案', insurCompanyPlanCode: '' } as any)
    result.forEach((ele:any, i:number) => {
        insuranceDate.value[i] = ele.planAlias
    })
    console.log(result, 'resultresultresult')

    // 保险方案数据赋值
    insuranceDatec.value = result
    console.log(
        insuranceDate.value[datePlan.value],
        'insuranceDatainsuranceData'
    )
}
const insuranceDatec = ref([] as any)
/* 全部保司 全部保司 弹窗 */
const longCompanyName = ref([] as string[])
const sortIndex = ref(0)
const bindPickerChangeCompany = async function (e: { detail: { value: string } }) {
    sortIndex.value = Number(e.detail.value)
    // insuranceDetail()
    console.log(sortIndex.value, 'sortIndex发生改变')
    await insuranceData()
}

// 保险数据
// 调用保险数据接口
const insuranceData = async function () {
    console.log(insuranceDatec.value, datePlan.value, insuranceDatec.value[datePlan.value], 'gsuhgysghuyshuy')

    const data = await getInsureData({
        startTime:
            timeIndex.value !== 1000
                ? startTime.value
                : itemRangeOne.value
                    ? itemRangeOne.value
                    : startTime.value || startTime.value,
        endTime:
            timeIndex.value !== 1000
                ? endTime.value
                : itemRangeTwo.value
                    ? itemRangeTwo.value
                    : endTime.value,
        insurCompanyPlanCode: datePlan.value === 0 ? '' : insuranceDatec.value[datePlan.value].insurCompanyPlanCode,
        insurCompanyCode: sortIndex.value === 0 ? '' : longCompanyName.value[sortIndex.value - 1][0]
    })
    console.log(data, 'datadata')
    console.log(
        insuranceDate.value[datePlan.value],
        'insuranceDatainsuranceData'
    )
    insureDate.value = data
}

// '昨天', '今天', '明天', '本月' 切换函数
const itemRangeOne = ref('')
const itemRangeTwo = ref('')
const itemRange = ref('' as string | undefined)
const selectTimeList = ref(['昨天', '今天', '本周', '本月', '上月'])
const timeIndex = ref(3)

// '昨天', '今天', '明天', '本月' 切换函数
const onCancel = async (index: { index: number; time: undefined | string }) => {
    console.log(index, 'indexindex')
    timeIndex.value = Number(index.index)
    itemRange.value = index.time
    if (index.index === 1000) {
        itemRangeOne.value = itemRange.value.substring(0, 10)
        itemRangeTwo.value = itemRange.value.substring(13, 23)
    } else {
        // eslint-disable-next-line no-unused-expressions
        startTime.value = index.startTime
        // eslint-disable-next-line no-unused-expressions
        endTime.value = index.endTime
    }

    console.log('切换了吗')
    await insuranceData()
}

// 统计数据
const statisticsData = ref()
const MethodStatistics = async () => {
    try {
        const result = await getMethodStatistics({
            queryMonth: dateTwo.value
        })
        console.log(result, 'getMethodStatisticsgetMethodStatistics')
        statisticsData.value = result
        const arr = statisticsData.value.filter((key: any) =>
            key.programme.indexOf('打包扫描') > 0)
        console.log(arr, '这个分隔的数组是啥getDigits')

        const arr2 = arr.map((key: any, i: any) => {
            const reorder = toNumber(key.programme.replace(/[^0-9]/ig, ""))
            arr[i].reorder = reorder
        })
        const arr3 = arr.sort(compare('reorder'))

        const arr4 = statisticsData.value.filter((key: any) =>
            key.programme.indexOf('打包扫描') < 0).concat(arr3)
        console.log(arr2, 'arr2', arr3, 'arr3')
        console.log(arr4, 'arr4')
        // arr.sort(compare())
        console.log(statisticsData.value, 'statisticsData11111111111111')
        console.log(statisticsData, 'statisticsData11111111111111')
        chartsDataPie1.value.series[0].data = result.map(
            (item: { premium: number; programme: string }) => {
                return {
                    name: item.programme,
                    value: item.premium,
                    ...item
                }
            }
        )
    } catch (error) {
        console.log(error, '错误信息是什么') // getdata error
    }
}

// 月份部分
const getCurrentMonth = () => {
    const date = new Date()
    const year = date.getFullYear()
    let month = date.getMonth() + 1
    month = month > 9 ? month : '0' + month
    return `${year}-${month}`
}

const date = ref(
    getCurrentMonth().substring(0, 4) +
    '年' +
    getCurrentMonth().substring(5, 8) +
    '月'
)
const dateTwo = ref(getCurrentMonth())
const bindDateChange = function (e: any) {
    console.log(e.target.value, '11111111111112')
    const time =
        e.target.value.substring(0, 4) +
        '年' +
        e.target.value.substring(5, 8) +
        '月'
    console.log(time, 'yearyearyearyear')
    date.value = time
    console.log(e.target.value, '1111111111111')
    console.log(date, 'datedate')
    dateTwo.value = e.target.value
    MethodStatistics()
}

// 日日保 运营数据
const operate = ref({} as OperateDataDto)
const OperateData = async () => {
    const result = await getOperateData({
        startTime: startTime.value,
        endTime: endTime.value
    })
    console.log(result, '运营数据运营数据')
    operate.value = result
    console.log(operate, 'integerintegerintegerintegerinteger')
}

// 近7日开通趋势
const dredgeCurrent = async () => {
    const result = await getDredgeCurrent()
    console.log(result, '近7日开通趋势')
    console.log(result.date, '近7日开通趋势datedate')
    console.log(result.openCount, '近7日开通趋势openCount')
    // res.categories.value = result.date
    chartData.value.series[0].data = result.openCount
    chartData.value.categories = result.date.map((item: string, index: number) => {
        chartData.value.series[0].data.push({
            value: result.openCount[index]
        })
        // console.log(item.split('-')[1], '------')
        return item.split('-')[1] + '/' + item.split('-')[2]
    })
}
onMounted(async () => {
    insuranceData()
    insurancePlan()
    MethodStatistics()
    OperateData()
    dredgeCurrent()
})
</script>
<style lang="scss" scoped>
.container {
    min-height: 100vh;
    background: #fafafc;
    padding-bottom: 89rpx;
}

.tab-box {
    display: flex;
    align-items: center;
    justify-content: center;
}

.tab-radius {
    margin-top: 30rpx;
    padding: 0rpx 30rpx;
}

.scroll {
    height: 100vh;
}

.record-list {
    margin-top: 34rpx;

    .record-i {
        padding: 30rpx;
        background: #ffffff;
        border-radius: 16rpx;
    }

    .info-row {
        display: flex;
    }

    .info-row-left {
        width: 138rpx;
        color: $grey;
        font-size: $font-normal;
        margin-bottom: 17rpx;
    }

    .info-row-right {
        color: $black;
        font-size: $font-normal;
        margin-bottom: 17rpx;
    }
}

// 销售记录列表
.sale-list {
    padding: 30rpx;

    .sale-time {
        display: flex;
        align-items: center;
    }

    .sale-fixed-width {
        width: 42rpx;
    }

    .decorate-time {
        width: 29rpx;
        height: 29rpx;
        border: 2px solid #dee0e3;
        border-radius: 50%;
        @include flex-center;
    }

    .decorate-within {
        width: 15rpx;
        height: 15rpx;
        background: #dee0e3;
        border-radius: 50%;
    }

    .time {
        color: $black;
        font-size: $font-normal;
    }

    .sale-content {
        margin: 13rpx 0 13rpx 18rpx;
        border-left: 1rpx solid #dee0e3;
        display: flex;
        align-items: center;
        padding-left: 25rpx;
    }

    .sale-line {
        height: 100%;
    }

    .sale-content-box {
        padding: 25rpx 0;
        flex: 1;

        .box {
            padding: 30rpx;
            background: #ffffff;
            border-radius: 16rpx;
        }

        .row-i {
            color: $grey;
            font-size: $font-normal;
        }

        .row-i-active {
            margin-bottom: 24rpx;
        }

        .num {
            color: $black;
            font-size: $font-normal;
        }
    }
}

.operate {
    padding: 30rpx;
    background: #ffffff;
    border-radius: 16rpx;

    .operate-screen {
        .title {
            color: #202536;
            font-size: $font-normal;
        }
    }

    .screen-i {
        border-radius: 8rpx;
        border: 1rpx solid #dee0e3;
        padding: 12rpx 15rpx;
        color: #565868;
        font-size: $font-base;
    }

    .drop-down {
        width: 22rpx;
        height: 20rpx;
    }

    .box-list {
        @include flex-between;
        flex-wrap: wrap;
        margin: 30rpx 0 30rpx 0;
    }

    .block-box-i {
        width: calc(100% / 2.6);
        background: #f4f4f7;
        padding: 23rpx 0 23rpx 30rpx;
        border-radius: 16rpx;

        .title {
            color: #565868;
            // font-weight: bold;
        }

        .num {
            color: $black;
            font-weight: bold;
            font-size: $font-large;
            margin-top: 10rpx;
        }

        .company {
            font-size: $font-small;
        }
    }

    .block-box-i-active {
        flex: 1;
    }
}

.cell {
    font-size: 24rpx;
}

.operate-top {
    margin: 30rpx 0;

    .operate-title {
        .title {
            color: $black;
            font-size: $font-normal;
        }
    }

    .operate-chart {
        margin-top: 52rpx;
        height: 400rpx;
    }

    .qiun-data-charts {
        height: 400rpx;
        width: 200rpx;
    }

    .qiun-data-charts-bg {
        background: #fafafc;
        margin-top: 30rpx;
        border-radius: 16rpx;
        padding: 10rpx 10rpx;
    }

    .operate-table {
        margin-top: 20rpx;

        .table-title {
            border: 16rpx 16rpx;
        }

        .title {
            width: calc(100% / 3);
            text-align: center;
            height: 88rpx;
            line-height: 88rpx;
            background: #f4f4f7;
        }

        .cell {
            width: calc(100% / 3);
            text-align: center;
            height: 88rpx;
            line-height: 88rpx;
            background: #fafafc;
            color: #565868;
            font-size: 25rpx;
        }

        .cell-active {
            display: flex;
            align-items: center;
        }

        .colour-block {
            border-radius: 4rpx;
            width: 16rpx;
            height: 16rpx;
            margin: 0 12rpx 0 30rpx;
            font-size: 25rpx;
        }
    }
}

.time-date ::v-deep .uni-calendar__mask {
    top: 30%;
    margin-top: 50rpx;
}

.time-date ::v-deep .uni-calendar__header-mobile {
    padding-top: 300rpx;
}

uni-calendar__content uni-calendar--fixed uni-calendar--ani-show uni-calendar__content-mobile {
    margin-top: 550rpx;
}

.fatalism-right {
    margin-right: 30rpx;
}

.cell-align {
    display: flex;
    align-items: center;
}

.charts-box {
    background: #FAFAFC;
}
</style>
